package cn.yunhe.aspect;

import cn.yunhe.exception.OutOfStockException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;



@Aspect
@Component
public class LogAspect {
    @Pointcut("execution(void *Phone(int))")
    public void kong(){
    }
@Before("kong()")
    public void before1(JoinPoint jp) {
        Object[] args = jp.getArgs();//被拦截下的方法的参数数组
        String methodName = jp.getSignature().getName();//被拦截下的方法名
        if ("butPhone".equals(methodName)) {
            System.out.println("日志" + currentTime() + args[0] + "部");
        }
    }
@AfterReturning("kong()")
    public void afterReturn(JoinPoint jp) {
        String method = jp.getSignature().getName();
        System.out.println(currentTime() + "方法名" + method);

    }
@AfterThrowing(pointcut = "kong()",throwing = "oe")
    public void afterThrowing(JoinPoint js, OutOfStockException oe) {
        String methodName = js.getSignature().getName();
        System.out.println(currentTime() + methodName + "发生了异常,信息为:" + oe.getMessage());

    }
@After("kong()")
    public void after2(JoinPoint jp) {
        String memothed = jp.getSignature().getName();
        if ("butPhone".equals(memothed)) {
            System.out.println("日志" + currentTime() + "进货完毕，发生异常依然执行");
        }
        if ("salePhone".equals(memothed)) {
            System.out.println("日志" + currentTime() + "售货完毕，发生异常依然执行");
        }
    }
@Around("kong()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        String methodName = pjp.getSignature().getName();
        long start = System.currentTimeMillis();
        System.out.println("start==" + start);
        System.out.println(currentTime() + methodName + "方法开始执行");

        try {
            return pjp.proceed();
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("end===" + end);
            System.out.println(currentTime() + "执行wanbi" + (end - start));

        }
    }


    public String currentTime() {
        SimpleDateFormat af = new SimpleDateFormat();
        return af.format(new Date());
    }

}
